/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package ticketmanager;

/**
 *
 * @author Viktor
 */
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.ArrayList;

/**
 *
 * @author Viktor
 */
public class TicketManager {
    //Get ticket list from database and returns RAW list of them
    public List<Ticket> getTickets(Connection conn) {
        List<Ticket> newList = new ArrayList<Ticket>();
        String querySQL = "SELECT TTS.ROW_ID, TTS.TITLE, TTS.STATUS, EMP.EMP_NAME, TTS.TT_CATEG, TTS.DESCRIPTION " +
                           "FROM TICKETS TTS, " +
                                "EMPLOYEE EMP " +
                           "WHERE TTS.SOLVER_ID = EMP.ROW_ID(+)";
        PreparedStatement pStmt;
        ResultSet rSet;

        try {
            pStmt = conn.prepareStatement(querySQL);
            rSet = pStmt.executeQuery();

            while(rSet.next()) {
                Ticket ticket = new Ticket();

                ticket.setRowID(rSet.getString(1));
                ticket.setTitle(rSet.getString(2));
                ticket.setStatus(rSet.getString(3));
                ticket.setSolver(rSet.getString(4));
                ticket.setCategory(rSet.getString(5));
                ticket.setDescription(rSet.getString(6));
                ticket.setFollow(true);
                ticket.setFresh(true);

                newList.add(ticket);
            }
            rSet.close();
            pStmt.close();
        }
        catch (SQLException e) {
            return null;
        }


        return new ArrayList<Ticket>(newList);
    }

    /*Compares current list and new list of tickets and merges them.
     If ticket already exists in current list then [fresh] flag will be set to false.
     Method returns medged list where Only new tickets marked with flag [fresh]*/
    public List<Ticket> mergeTickets(List<Ticket> currentList, List<Ticket> newList) {
        List<Ticket> mergedList = new ArrayList<Ticket>(newList);

        if(currentList.size() > 0 && newList.size() > 0) {
            for(Ticket mergedTicket: mergedList)
                 for(Ticket currentTicket: currentList) {
                    if(mergedTicket.equals(currentTicket)) {
                        mergedTicket.setFresh(false);
                        if (!currentTicket.getFollow())
                            mergedTicket.setFollow(false);
                    }
                }
        }

        return new ArrayList<Ticket>(mergedList);
    }

    public Integer countFreshTickets(List<Ticket> ticketList) {
        Integer count = 0;

        for(Ticket ticket: ticketList) {
            if (ticket.getFresh())
                count++;
        }

        return new Integer(count);
    }
}
